package com.lianjing.sh.acceleo.controller.mvc.controller.io.output;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.uml2.uml.Classifier;
import org.eclipse.uml2.uml.Property;

import com.lianjing.sh.acceleo.controller.tool.query.Class_Common;

public class Output_Service {

	private static final Class_Common Class_Common = new Class_Common();
	
	/**
	 * 基础数据：
	 * {
	 * 	name_1 : null
	 * 	object_1 : {
	 * 		name_2 : null
	 * 		object_2 : {
	 * 				name_3 : null
	 * 				object_3 : {}
	 * 				age_3 : null
	 * 			}
	 * 		age_2 : null
	 *	}
	 * 	age_1 : null
	 * }
	 * 	->
	 * [
	 *	[name_1]
	 *	[object_1, name_2]
	 *	[object_1, object_2, name_3]
	 *	[object_1, object_2, age_3]
	 *	[object_1, age_2]
	 *	[age_1]
	 * ]
	 * 
	 */
	public List<List<Property>> getPropertyPathFields(Classifier aClass){
		List<List<Property>> list = new ArrayList<>();
		Map<Property, Property> propertyChildParentMap = toPropertyChildParentMap(aClass, null);
		for(Property item : propertyChildParentMap.keySet()){
			list.add(getPropertyPath(item, propertyChildParentMap));
		}
		return list;
	}
	
	/**
	 * 基础数据：
	 * {
	 * 	name_1 : null
	 * 	object_1 : {
	 * 		name_2 : null
	 * 		object_2 : {
	 * 				name_3 : null
	 * 				object_3 : {}
	 * 				age_3 : null
	 * 			}
	 * 		age_2 : null
	 *	}
	 * 	age_1 : null
	 * }
	 * 
	 * {key: name_1 -> value: null}	-> [name_1]
	 * {key: name_3 -> value: object_2}-> [object_1, object_2, name_3]
	 * 	
	 */
	private List<Property> getPropertyPath(Property property, Map<Property, Property> properties){
		List<Property> list = null;
		Property value = properties.get(property);
		if(value != null){
			list = getPropertyPath(value, properties);
		}else{
			list = new ArrayList<>();
		}
		list.add(property);
		return list;
	}
	
	/**
	 * {
	 * 	name_1 : null
	 * 	object_1 : {
	 * 		name_2 : null
	 * 		object_2 : {
	 * 				name_3 : null
	 * 				object_3 : {}
	 * 				age_3 : null
	 * 			}
	 * 		age_2 : null
	 *	}
	 * 	age_1 : null
	 * }
	 * 	->
	 * {
	 * 	{key: name_1 -> value: null} ,
	 * 	{key: object_1 -> value: null} ,
	 * 		{key: name_2	-> value: object_1} ,	
	 * 		{key: object_2 ->value: object_1} ,
	 * 			{key: name_3 -> value: object_2} ,
	 * 			{key: object_3 -> value: object_2} ,
	 * 			{key: age_3 -> value: object_2} ,
	 * 		{key: age_2 -> value: object_1} ,
	 * 	{key: age_1 -> value: null}
	 * }
	 * 说明：
	 *	{key: property -> value: parent}
	 * 
	 */
	private Map<Property, Property> toPropertyChildParentMap(Classifier aClass, Property parent){
		Map<Property, Property> map = new LinkedHashMap<>();
		for(Property p : Class_Common.getDirectedPropertyFields(aClass)){
			if(Class_Common.isClassPropertyField(p)){
				if(((Classifier)p.getOwner()).getAssociations().contains(p.getAssociation())){
					map.putAll(toPropertyChildParentMap((Classifier)p.getType(), p));
				}else{
					map.put(p, parent);
				}
			}else{
				map.put(p, parent);
			}
		}
		return map;
	}
	
}
